package com.gin.web;

import com.gin.web.dto.ResultMsg;
import com.gin.web.exp.BasicException;
import com.gin.web.exp.ExpCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 基本控制器
 */
public class BasicController {

    private Logger logger = LoggerFactory.getLogger(BasicController.class);


    /**
     * 统一处理：异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler
    public ResultMsg handlerExp(Exception e) {
        logger.error("", e);
        if (e instanceof BasicException) { // 处理自定义异常
            BasicException exp = (BasicException) e;
            return this.buildErrorData(exp.expCode);
        }
        return this.buildErrorData(ExpCode.ERROR_CODE, ExpCode.ERROR_CODE.msg + e.getMessage());
    }

    /**
     * 构建正确的数据返回对象
     *
     * @param data 数据
     * @param <T>
     * @return
     */
    public <T> ResultMsg buildSuccessData(T data) {
        ResultMsg<T> msg = new ResultMsg();
        return msg.buildSuccessData(data);
    }

    /**
     * 构件错误的信息
     *
     * @param serviceCode 错误code
     * @return
     */
    public ResultMsg buildErrorData(ExpCode serviceCode) {
        ResultMsg msg = new ResultMsg();
        return msg.buildError(serviceCode);
    }

    /**
     * 构建错误信息
     *
     * @param serviceCode
     * @param msgText
     * @return
     */
    public ResultMsg buildErrorData(ExpCode serviceCode, String msgText) {
        ResultMsg msg = new ResultMsg();
        msg.buildError(serviceCode);
        msg.setMsg(msgText);
        return msg;
    }

    /**
     * 处理成功：返回成功或者失败
     *
     * @param flag
     * @return
     */
    public ResultMsg buildHandlerData(boolean flag) {
        ResultMsg msg = new ResultMsg();
        if (flag) {
            msg.buildError(ExpCode.SUCCESS_CODE);
        } else {
            msg.buildError(ExpCode.HANDLER_ERROR);
        }
        msg.setSuccess(flag);
        return msg;
    }
}
